<template>
  <div>
    <div class="box">
      <el-form>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品货号">
              <el-input
                size="large"
                placeholder="商品货号"
                v-model="requestParam.data.id"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="名称">
              <el-input
                size="large"
                :placeholder="'名称'"
                v-model="requestParam.data.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 条形码 -->
          <el-col :span="6">
            <el-form-item label="条形码">
              <el-input
                size="large"
                :placeholder="'条形码（光标在此处，便可扫描）'"
                v-model="requestParam.data.barCode"
                autocomplete="off"
                clearable
                @keyup.enter.native="getBodyData()"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 最低单价 -->
          <el-col :span="6">
            <el-form-item label="最低单价">
              <el-input-number v-model="requestParam.data.minPrice" />
            </el-form-item>
          </el-col>

          <!-- 最高单价 -->
          <el-col :span="6">
            <el-form-item label="最高单价">
              <el-input-number v-model="requestParam.data.maxPrice" />
            </el-form-item>
          </el-col>

          <!-- 最低库存 -->
          <el-col :span="6">
            <el-form-item label="最低库存">
              <el-input-number v-model="requestParam.data.minStock" />
            </el-form-item>
          </el-col>

          <!-- 最高库存 -->
          <el-col :span="6">
            <el-form-item label="最高库存">
              <el-input-number v-model="requestParam.data.maxStock" />
            </el-form-item>
          </el-col>

          <!-- 最低批发价 -->
          <el-col :span="6">
            <el-form-item label="最低批发价">
              <el-input-number v-model="requestParam.data.minWholesalePrice" />
            </el-form-item>
          </el-col>

          <!-- 最高批发价 -->
          <el-col :span="6">
            <el-form-item label="最高批发价">
              <el-input-number v-model="requestParam.data.maxWholesalePrice" />
            </el-form-item>
          </el-col>

          <!-- 最低起订量 -->
          <el-col :span="6">
            <el-form-item label="最低起订量">
              <el-input-number v-model="requestParam.data.minMinOrder" />
            </el-form-item>
          </el-col>

          <!-- 最高起订量 -->
          <el-col :span="6">
            <el-form-item label="最高起订量">
              <el-input-number v-model="requestParam.data.maxMinOrder" />
            </el-form-item>
          </el-col>

          <!-- 分类选择器 -->
          <el-col :span="6">
            <el-form-item label="商品分类">
              <el-button
                v-if="goodsType.id == null"
                @click.prevent="toSelectType()"
                >选择商品分类</el-button
              >
              <el-button v-else @click.prevent="toSelectType()">{{
                goodsJs.getGoodsTypeFullName(goodsType)
              }}</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item>
              <el-radio-group v-model="isTop" class="ml-4">
                <el-radio :label="true" size="large">最上级分类</el-radio>
                <el-radio :label="false" size="large">展开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 查询 -->
          <el-col :span="6">
            <el-form-item>
              <el-button
                size="large"
                type="primary"
                @click.prevent="getBodyData()"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="box">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>商品</span>
            <el-button
              style="float: right"
              size="mini"
              type="primary"
              @click.prevent="toSave('')"
              >新增</el-button
            >
            <el-button
              style="float: right; margin-right: 10px"
              size="mini"
              type="danger"
              @click.prevent="toRemoveBatch()"
              >删除</el-button
            >
          </div>
        </template>

        <el-table
          ref="table"
          @selection-change="selectionChange"
          :reserve-selection="true"
          v-loading="loading"
          element-loading-text="Loading..."
          :data="bodyData.content"
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          max-height="500px"
        >
          <el-table-column type="selection" width="55" />

          <!-- 序号 -->
          <el-table-column type="index" label="序号" width="55" />

          <!-- 名称 -->
          <el-table-column prop="name" label="名称" width="120" />

          <!-- 商品货号 -->
          <el-table-column prop="numberStr" label="商品货号" width="120" />

          <!-- 展示图 -->
          <el-table-column prop="fileIdOfImgArr" label="展示图" width="120">
            <template #default="{ row }">
              <el-image
                v-if="
                  getFileIdOfImgArr(row.fileIdOfImgArrStr) != null &&
                  getFileIdOfImgArr(row.fileIdOfImgArrStr).length > 0
                "
                style="width: 100px; height: 100px"
                :src="
                  $kt.file.visit(getFileIdOfImgArr(row.fileIdOfImgArrStr)[0])
                "
                fit="contain"
                :preview-src-list="
                  getPreviewSrcList(getFileIdOfImgArr(row.fileIdOfImgArrStr))
                "
                :preview-teleported="true"
              ></el-image>
              <div v-else>无</div>
            </template>
          </el-table-column>

          <!-- 条形码 -->
          <el-table-column prop="barCode" label="条形码" width="200">
            <template #default="{ row }">
              <div
                v-if="row.barCode != null && row.barCode != ''"
                @click="openBarCode(row)"
                style="text-align: center"
              >
                <div>
                  {{ row.barCode }}
                </div>
                <div style="font-size: 10px">(点击查看条形码)</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            v-if="false"
            prop="barCode"
            label="条形码图片"
            width="200"
          >
            <template #default="{ row }">
              <div v-if="row.barCode != null && row.barCode != ''">
                <img
                  @click="openBarCode(row)"
                  :id="'jsbarcodeImg' + row.id"
                  style="width: 200px"
                />
              </div>
            </template>
          </el-table-column>

          <!-- 单价 -->
          <el-table-column prop="price" label="单价" width="120" />

          <!-- 分类 -->
          <el-table-column prop="type" label="分类" width="180">
            <template #default="{ row }">
              <div v-if="row.type != null && row.type.name != null">
                {{ goodsJs.getGoodsTypeFullName(row.type) }}
              </div>
            </template>
          </el-table-column>

          <!-- 库存预警下限 -->
          <el-table-column
            prop="stockWarningLower"
            label="库存预警下限"
            width="120"
          />

          <!-- 库存预警上限 -->
          <el-table-column
            prop="stockWarningUpper"
            label="库存预警上限"
            width="120"
          />

          <!-- 零售价 -->
          <el-table-column prop="retailPrice" label="零售价" width="120" />

          <!-- 批发价 -->
          <el-table-column prop="wholesalePrice" label="批发价" width="120" />

          <!-- 采购价 -->
          <el-table-column prop="purchasePrice" label="采购价" width="120" />

          <!-- 起订量 -->
          <el-table-column prop="minOrder" label="起订量" width="120" />

          <!-- 优先级 -->
          <el-table-column prop="priority" label="优先级" width="120" />

          <el-table-column prop="gmtCreate" label="创建时间" width="120">
            <template #default="{ row }">
              {{ new Date(row.gmtCreate).toLocaleDateString() }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="toEdit(scope.row)"
              >
                <el-icon> 修改 </el-icon>
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="toAddChildren(scope.row)"
              >
                添加单品
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="openBarCode(scope.row)"
              >
                打印条形码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="position: relative; height: 30px">
          <el-pagination
            @current-change="pageChange"
            style="
              position: absolute;
              left: 50%;
              top: 10px;
              transform: translateX(-50%);
            "
            layout="prev, pager, next"
            :page-size="requestParam.pageSize"
            :current-page="requestParam.pageNumber"
            :total="bodyData.totalElements"
          />
        </div>
      </el-card>
    </div>

    <DialogOfSave ref="dialogOfSave" @submit="getBodyData()" />
    <GoodsTypeSelect
      ref="goodsTypeSelect"
      @select="goodsSelectSelect"
    ></GoodsTypeSelect>
    <BarDialog ref="barDialog" />
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import $kt from "@/vueKantboot";
import DialogOfSave from "./components/DialogOfSave.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ro } from "element-plus/es/locale";
import GoodsTypeSelect from "@/components/goodsTypeSelect/goodsTypeSelect.vue";
import goodsJs from "@/commonJs/goods/index.js";
import JsBarcode from "jsbarcode";
import BarDialog from "@/components/barDialog/barDialog.vue";

let dialogOfSave = ref();

let table = ref();

let barDialog = ref();
let goodsTypeSelect = ref();

let openBarCode = (row: any) => {
  if (row.barCode == null || row.barCode == "") {
    ElMessage({
      message: "条形码为空",
      type: "error",
    });
    return false;
  }
  barDialog.value.open(row);
};

let toSave = (param: any) => {
  dialogOfSave.value.open(param);
};

let toSelectType = (param: any) => {
  goodsTypeSelect.value.open();
};

let goodsType = ref({
  id: null,
  name: null,
});

let requestParam = ref({
  data: {
    id: null,
    code: null,
    name: null,
    numberStr: null,
    minPrice: null,
    maxPrice: null,
    barCode: null,
    minStock: null,
    maxStock: null,
    typeId: null,
    priority: null,
    minPurchasePrice: null,
    maxPurchasePrice: null,
    minWholesalePrice: null,
    maxWholesalePrice: null,
    minRetailPrice: null,
    maxRetailPrice: null,
    minMinOrder: null,
    maxMinOrder: null,
  },
  pageNumber: 1,
  pageSize: 30,
});

let goodsSelectSelect = (res: any) => {
  requestParam.value.data.typeId = res.id;
  goodsType.value = res;
};

let isTop = ref(true);

let bodyData = ref({
  content: [
    {
      id: 1,
      barCode: "a",
      brandId: null,
      // 编码
      code: null,
      gmtCreate: null,
      gmtModified: null,
      // 起订量
      minOrder: null,
      // 名称
      name: null,
      fileIdOfImgArrStr: "[]",
      fileIdOfImgArr: [],
      numberStr: null,
      price: 100.0,
      priority: null,
      purchasePrice: null,
      retailPrice: null,
      selectList: [
        {
          busGoodsAttrSelect: {
            attrId: 1,
            code: null,
            gmtCreate: null,
            gmtModified: null,
            id: 1,
            value: "sss",
          },
          gmtCreate: null,
          gmtModified: null,
          goodsId: 1,
          id: 1,
          selectId: 1,
        },
      ],
      stock: null,
      stockWarningLower: null,
      stockWarningUpper: null,
      type: null,
      typeId: null,
      unitId: null,
      wholesalePrice: null,
      barCodeSvg: null,
    },
  ],
  totalElements: 0,
});

let selection = ref([]);

let selectionChange = (val: any) => {
  selection.value = val;
};

let toEdit = (param: any) => {
  dialogOfSave.value.open(param);
};

let pageChange = (val: any) => {
  requestParam.value.pageNumber = val;
  getBodyData();
};

let toAddChildren = (param: any) => {
  dialogOfSave.value.open({
    id: "",
    name: "",
    parentId: param.id,
    typeId: param.typeId,
  });
};

let loading = ref(true);

let createBarCode = (row: any) => {
  if (row.barCode == null || row.barCode == "") {
    return false;
  }
  setTimeout(() => {
    JsBarcode("#jsbarcodeImg" + row.id, row.barCode, {
      format: "CODE39",
      width: 2,
      height: 40,
    });
  }, 500);
};

let getBodyData = () => {
  loading.value = true;

  if (isTop.value) {
    $kt.request
      .request({
        url: "/business-goods-web/admin/goods/getBodyDataTop",
        method: "post",
        data: requestParam.value,
      })
      .then((res) => {
        if (res.data.success) {
          bodyData.value = res.data.data;
          for (let i = 0; i < bodyData.value.content.length; i++) {
            // createBarCode(bodyData.value.content[i]);
            if (
              bodyData.value.content[i].fileIdOfImgArrStr == null ||
              bodyData.value.content[i].fileIdOfImgArrStr == ""
            ) {
              bodyData.value.content[i].fileIdOfImgArrStr = "[]";
            }
            bodyData.value.content[i].fileIdOfImgArr = JSON.parse(
              bodyData.value.content[i].fileIdOfImgArrStr
            );
          }
        }
        loading.value = false;
      });
    return false;
  }

  $kt.request
    .request({
      url: "/business-goods-web/admin/goods/getBodyData",
      method: "post",
      data: requestParam.value,
    })
    .then((res) => {
      if (res.data.success) {
        bodyData.value = res.data.data;
      }
      loading.value = false;
    });
};

let getFileIdOfImgArr = (fileIdOfImgArrStr: any) => {
  if (fileIdOfImgArrStr == null || fileIdOfImgArrStr == "") {
    return [];
  }
  return JSON.parse(fileIdOfImgArrStr);
};

getBodyData();

let removeBatch = () => {
  $kt.request
    .request({
      url: "/business-goods-web/admin/goods/removeBatch",
      method: "post",
      data: selection.value,
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        getBodyData();
        return false;
      }
      ElMessage({
        message: res.data.errMsg,
        type: "error",
      });
    });
};

let toRemoveBatch = () => {
  if (selection.value.length == 0) {
    ElMessage({
      message: "请选择要删除的数据",
      type: "error",
    });
    return false;
  }

  // 询问是否删除
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 删除
      removeBatch();
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

let getPreviewSrcList = (fileIdOfImgArr: any) => {
  let arr = [];
  for (let i = 0; i < fileIdOfImgArr.length; i++) {
    arr.push($kt.file.visit(fileIdOfImgArr[i]));
  }
  return arr;
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px 20px 0 20px;
}

.box-box {
  background-color: #fff;
  color: #fff;
  text-align: center;
  padding: 30px;
  border-radius: 5px;
}

.box-box:hover {
  // 变小
  transform: scale(0.95);
}

.box-box:active {
  // 变小
  transform: scale(0.9);
}
</style>
